package ar.com.tallerdos.smartdinner.sync;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public abstract class Tarea {
    public static final String SERVER_URL = "http://10.0.2.2/cake_2_4_6";
//    public static final String SERVER_URL = "http://192.168.0.51/prueba";

    public static final String SEPARADOR_ID = ",";
    
    public abstract Integer realizarTarea();    
    
    protected String llamarWebService(String url) {
	return llamarWebService(url, null);
    }

    protected String llamarWebService(String url, List<NameValuePair> args) {
	InputStream is = null;

	try {
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(url);
	    if (args != null) {
		httppost.setEntity(new UrlEncodedFormEntity(args));
	    }
	    HttpResponse response = httpclient.execute(httppost);
	    HttpEntity entity = response.getEntity();
	    is = entity.getContent();
	    Log.i("log_tag", "Conexión exitosa");
	} catch (Exception e) {
	    Log.e("log_tag", "Error en conexión http" + e.toString());
	}

	return convertToString(is);
    }

    protected String convertToString(InputStream is) {
	String result = "";

	try {
	    BufferedReader reader = new BufferedReader(new InputStreamReader(
		    is, "iso-8859-1"), 8);
	    StringBuilder sb = new StringBuilder();
	    String line = null;
	    while ((line = reader.readLine()) != null) {
		sb.append(line + "\n");
	    }
	    is.close();

	    result = sb.toString();
	    Log.i("log_tag",
		    "Conversion Exitosa del resultado" + result.toString());
	} catch (Exception e) {
	    Log.e("log_tag",
		    "Error en conversion del resultado " + e.toString());
	}

	return result;
    }
    
    public void onPostExecute() {
	
    }

}
